﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace ActionSystem.Core.Utils
{

    /// <summary>
    /// 通用对象池,直接生成对象的
    /// 如何一开始就初始化好是个问题?用的时候初始化难免造成一次卡顿
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class GeneticPool<T> where T : IPoolItem, new()
    {
        private const int INIT_DELTA_CAPACITY = 20;
        private static List<T> buffers = new List<T>();
        private static int delta_capacity = INIT_DELTA_CAPACITY;


        /// <summary>
        /// 预先初始化对象池，填充元素
        /// </summary>
        /// <param name="capacity">初始容量</param>
        public static void PreInitPool(int capacity = INIT_DELTA_CAPACITY)
        {
            for (int i = 0; i < capacity; i++)
            {
                //创建
                var buff = new T();
                //放入池子
                buff.IsDeleted = true;
                buffers.Add(buff);
            }
        }
        //从池中获取
        public static T Create()
        {
            T buff;
            if(buffers.Count == 0)
            {
                PreInitPool(delta_capacity);
                delta_capacity *= 2;
            }

            buff = buffers[buffers.Count - 1];
            buffers.RemoveAt(buffers.Count - 1);                            
            buff.PoolItemReset();//重置
            buff.IsDeleted = false;
            return buff;
        }
        //放入池中
        public static void Delete(T item)
        {
            if (item.IsDeleted)
            {
                throw new System.Exception("Has Deleted");
            }
            else
            {
                item.IsDeleted = true;
                buffers.Add(item);
            }

        }

        public static int PoolCount
        {
            get { return buffers.Count; }
        }        
    }
}